package brwarner.game 
{
	import flash.events.EventDispatcher;
	import flash.geom.Point;
	/**
	 * ...
	 * @author Brook Jensen
	 */
	public class GameGrid extends EventDispatcher
	{
		//All the grid square states
		var _squares:Array;
		
		//Size of the grid
		var _size:Number;
		
		public function GameGrid( s:Number ) 
		{
			//Store size
			_size = s;
			
			//Create all the grid squares
			_squares = new Array();
			for ( var a = 0; a < _size; a++ )
			{
				for( var b = 0; b < _size; b++ )
				{
					//Create square
					var type:Number = 0;
					if( !GameConstants.USE_TEST_GRID )
						type = int(Math.random() * GridSquare.RANDOM_MAX);
					else
						type = GameConstants.TEST_GRID[a][b];
					var square:GridSquare = new GridSquare( this, type, b, a );
					_squares.push(square);
				}
			}
			refreshSprites();
		}
		
		private var _block:Boolean = false;
		public function set Block( b:Boolean ):void {
			_block = b;
		}
		public function get Block( ):Boolean { return _block; }
		
		public function refreshSprites( ):void {
			_squares.forEach( function( e:GridSquare, i:Number, a:Array ) {
				e.refreshSprite();
			});
		}
		
		private var _gameOver:Boolean = false;
		
		public function endGame( ) {
			_gameOver = true;
		}
		public function get GameOver():Boolean { return _gameOver; }
		
		public function inBounds( p:Point ):Boolean
		{
			return !( p.x < 0 || p.y < 0 || p.x >= GameConstants.GRID_SIZE || p.y >= GameConstants.GRID_SIZE);
		}
		
		//Checks the types of squares surrounding the one in question
		public function bubbleTypeTest( tile:Point, compare:Number ):Array {
			//Get array of points (UP, RIGHT, DOWN, LEFT)
			var result:Array = [ tile.add( new Point( 0, -1) ),
				tile.add( new Point( 1, 0 ) ),
				tile.add( new Point( 0, 1 ) ),
				tile.add( new Point( -1, 0 ) ) ];
			
			//Replace with the boolean checks
			for ( var i = 0; i < result.length; i++ ) {
				if ( inBounds( result[i] ) && getTile(result[i]).Type == compare ) result[i] = true;
				else result[i] = false;
			}
			return result;
		}
		
		public function update():void {
			_squares.forEach( function( e:GridSquare, i:Number, a:Array ) {
				e.update();
			});
		}
		
		//Gets a game tile
		public function getTile( tile:Point ) : GridSquare
		{
			return _squares[ tile.y * _size + tile.x ];
		}
		
	}

}